import React, { useState } from 'react';
import { Table, Input, Button, DatePicker, Card, Space, Tag, Select } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import ReactECharts from 'echarts-for-react';
import OverviewLayout from '../../layouts/OverviewLayout';
import moment from 'moment';

const { Option } = Select;

// 模拟采购数据
const mockPurchases = [
    {
        id: 'PO2023001',
        supplier: '建材供应商A',
        material: '钢筋',
        specification: 'HRB400 Φ20',
        quantity: 100,
        unit: '吨',
        unitPrice: 4800,
        totalAmount: 480000,
        orderDate: '2023-01-10',
        expectedDelivery: '2023-01-25',
        actualDelivery: '2023-01-23',
        purchaser: '采购员张三',
        status: '已完成',
        paymentStatus: '已付款',
        warehouse: '主仓库',
        remark: '一期工程使用'
    },
    {
        id: 'PO2023002',
        supplier: '五金供应商B',
        material: '电缆',
        specification: 'YJV 3*150+2*70',
        quantity: 5000,
        unit: '米',
        unitPrice: 120,
        totalAmount: 600000,
        orderDate: '2023-02-15',
        expectedDelivery: '2023-03-05',
        actualDelivery: '2023-03-10',
        purchaser: '采购员李四',
        status: '已完成',
        paymentStatus: '部分付款',
        warehouse: '电气仓库',
        remark: '商业中心项目'
    },
    {
        id: 'PO2023003',
        supplier: '混凝土供应商C',
        material: '商品混凝土',
        specification: 'C30',
        quantity: 300,
        unit: '立方米',
        unitPrice: 450,
        totalAmount: 135000,
        orderDate: '2023-03-20',
        expectedDelivery: '2023-03-25',
        actualDelivery: null,
        purchaser: '采购员王五',
        status: '进行中',
        paymentStatus: '未付款',
        warehouse: '临时仓库',
        remark: '地铁项目急需'
    }
];

// 可选的采购状态
const purchaseStatusOptions = [
    '已完成',
    '进行中',
    '已取消',
    '待审核'
];

const PurchaseOverview = () => {
    const [purchases] = useState(mockPurchases);
    const [filteredPurchases, setFilteredPurchases] = useState(mockPurchases);
    const [filters, setFilters] = useState({
        material: '',
        supplier: '',
        purchaser: '',
        status: undefined,
        startDate: null,
        endDate: null
    });

    // 处理筛选变化
    const handleFilterChange = (newValues) => {
        const newFilters = { ...filters, ...newValues };
        setFilters(newFilters);
        applyFilters(newFilters);
    };
    // 应用筛选条件
    const applyFilters = (filterParams) => {
        let result = [...purchases];

        if (filterParams.material) {
            result = result.filter(p => p.material.includes(filterParams.material));
        }

        if (filterParams.supplier) {
            result = result.filter(p => p.supplier.includes(filterParams.supplier));
        }

        if (filterParams.purchaser) {
            result = result.filter(p => p.purchaser.includes(filterParams.purchaser));
        }

        if (filterParams.status) {
            result = result.filter(p => p.status === filterParams.status);
        }

        if (filterParams.startDate && filterParams.endDate) {
            result = result.filter(p => {
                const orderDate = moment(p.orderDate, 'YYYY-MM-DD');
                return orderDate.isSameOrAfter(filterParams.startDate.startOf('day')) &&
                    orderDate.isSameOrBefore(filterParams.endDate.endOf('day'));
            });
        }

        setFilteredPurchases(result);
    };

    // 导出Excel
    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(filteredPurchases);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "采购订单列表");
        XLSX.writeFile(workbook, `采购订单列表_${moment().format('YYYYMMDD_HHmmss')}.xlsx`);
    };

    // 图表配置 - 采购状态分布
    const purchaseStatusOption = {
        title: {
            text: '采购订单状态分布',
            left: '3%',
            top: '3%'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: '5%',
            top: '3%',
            data: ['已完成', '进行中', '已取消', '待审核']
        },
        series: [
            {
                name: '采购状态',
                type: 'pie',
                radius: '80%',
                center: ['50%', '55%'],
                data: [
                    { value: 35, name: '已完成' },
                    { value: 20, name: '进行中' },
                    { value: 10, name: '已取消' },
                    { value: 5, name: '待审核' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    // 图表配置 - 月度采购金额
    const monthlyPurchaseOption = {
        title: {
            text: '月度采购金额',
            left: '3%',
            top: '3%'
        },
        tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>{a0}: {c0}元<br/>{a1}: {c1}元'
        },
        toolbox: {
            feature: {
                saveAsImage: {
                    title: '下载图片',
                    type: 'jpeg',
                    name: '月度采购金额统计',
                    backgroundColor: '#ffffff',
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                },
                dataView: {
                    title: '查看数据',
                    readOnly: true,
                    lang: ['数据表格', '关闭', '刷新'],
                    buttonColor: '#1890ff'
                },
                magicType: {
                    title: '切换图表',
                    type: ['line', 'bar']
                }
            },
            right: '20px',
            top: '10px'
        },
        grid: {
            top: '35%',
            right: '5%',
            left: '5%',
            bottom: '15%',
            containLabel: true
        },
        legend: {
            data: ['计划采购金额', '实际采购金额'],
            top: '3%'
        },
        xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: {
            type: 'value',
            name: '金额(元)'
        },
        series: [
            {
                name: '计划采购金额',
                type: 'line',
                data: [1200000, 1500000, 1800000, 2000000, 2200000, 2500000, 2300000],
                itemStyle: {
                    color: '#1890ff'
                }
            },
            {
                name: '实际采购金额',
                type: 'line',
                data: [1150000, 1450000, 1750000, 1950000, 2100000, 2400000, 2250000],
                itemStyle: {
                    color: '#52c41a'
                }
            }
        ]
    };

    // 表格列配置
    const columns = [
        {
            title: '采购单号',
            dataIndex: 'id',
            key: 'id',
            fixed: 'left',
            width: 120
        },
        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            width: 150
        },
        {
            title: '材料名称',
            dataIndex: 'material',
            key: 'material',
            width: 120
        },
        {
            title: '规格型号',
            dataIndex: 'specification',
            key: 'specification',
            width: 150
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            render: (text, record) => `${text} ${record.unit}`,
            width: 100
        },
        {
            title: '单价(元)',
            dataIndex: 'unitPrice',
            key: 'unitPrice',
            width: 100
        },
        {
            title: '总金额(元)',
            dataIndex: 'totalAmount',
            key: 'totalAmount',
            width: 120
        },
        {
            title: '下单日期',
            dataIndex: 'orderDate',
            key: 'orderDate',
            width: 120
        },
        {
            title: '预计/实际交付',
            key: 'delivery',
            render: (_, record) => (
                <span>
                    {record.expectedDelivery}<br/>
                    {record.actualDelivery || '未交付'}
                </span>
            ),
            width: 150
        },
        {
            title: '采购员',
            dataIndex: 'purchaser',
            key: 'purchaser',
            width: 100
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: status => {
                let color;
                switch (status) {
                    case '已完成':
                        color = 'green';
                        break;
                    case '进行中':
                        color = 'blue';
                        break;
                    case '已取消':
                        color = 'red';
                        break;
                    default:
                        color = 'orange';
                }
                return <Tag color={color}>{status}</Tag>;
            },
            width: 100
        },
        {
            title: '付款状态',
            dataIndex: 'paymentStatus',
            key: 'paymentStatus',
            render: status => {
                let color;
                switch (status) {
                    case '已付款':
                        color = 'green';
                        break;
                    case '部分付款':
                        color = 'blue';
                        break;
                    case '未付款':
                        color = 'red';
                        break;
                    default:
                        color = 'orange';
                }
                return <Tag color={color}>{status}</Tag>;
            },
            width: 100
        },
        {
            title: '仓库',
            dataIndex: 'warehouse',
            key: 'warehouse',
            width: 100
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 150
        }
    ];

    return (
        <OverviewLayout
            children={{
                topRight:
                    <ReactECharts
                        option={purchaseStatusOption}
                        style={{ height: '100%', width: '100%'}}
                    />,
                topLeft:
                    <ReactECharts
                        option={monthlyPurchaseOption}
                        style={{ height: '100%', width: '100%' }}
                    />,
                bottom:
                    <Card
                        title="采购订单列表"
                        variant={"borderless"}
                        style={{ height: 'calc((100vh - 64px) * 2 / 3)'}}
                        extra={
                            <Button
                                type="primary"
                                icon={<DownloadOutlined />}
                                onClick={exportToExcel}
                            >
                                导出Excel
                            </Button>
                        }
                    >
                        <Space style={{ marginBottom: 16 }}>
                            <Input
                                placeholder="材料名称"
                                value={filters.material}
                                onChange={e => handleFilterChange({ material: e.target.value })}
                                style={{ width: 150 }}
                            />
                            <Input
                                placeholder="供应商"
                                value={filters.supplier}
                                onChange={e => handleFilterChange({ supplier: e.target.value })}
                                style={{ width: 150 }}
                            />
                            <Input
                                placeholder="采购员"
                                value={filters.purchaser}
                                onChange={e => handleFilterChange({ purchaser: e.target.value })}
                                style={{ width: 150 }}
                            />
                            <Select
                                placeholder="选择状态"
                                value={filters.status}
                                onChange={value => handleFilterChange({ status: value })}
                                style={{ width: 150 }}
                                allowClear
                            >
                                {purchaseStatusOptions.map(status => (
                                    <Option key={status} value={status}>{status}</Option>
                                ))}
                            </Select>
                            <DatePicker.RangePicker
                                value={[filters.startDate, filters.endDate]}
                                onChange={(dates) => {
                                    handleFilterChange({
                                        startDate: dates ? dates[0] : null,
                                        endDate: dates ? dates[1] : null
                                    });
                                }}
                            />
                            <Button
                                type="default"
                                onClick={() => {
                                    const resetFilters = {
                                        material: '',
                                        supplier: '',
                                        purchaser: '',
                                        status: undefined,
                                        startDate: null,
                                        endDate: null
                                    };
                                    setFilters(resetFilters);
                                    applyFilters(resetFilters);
                                }}
                            >
                                重置
                            </Button>
                        </Space>
                        <Table
                            columns={columns}
                            dataSource={filteredPurchases}
                            rowKey="id"
                            pagination={{ pageSize: 10 }}
                            scroll={{ x: 2000 }}
                        />
                    </Card>
            }}
        />
    );
};

export default PurchaseOverview;